<template>
    <div class="preview-container">
        <div class="preview-content">
            <!-- 修改判断逻辑，处理字符串和对象两种情况 -->
            <template v-if="parsedContent && parsedContent.ext">
                <template v-if="parsedContent.ext === 'pdf'">
                    <iframe :src="previewUrl" class="preview-iframe"></iframe>
                </template>
                <template v-else-if="['xls', 'xlsx'].includes(parsedContent.ext)">
                    <preview-excel :src="previewUrl"></preview-excel>
                </template>
                <template v-else-if="['jpg', 'jpeg', 'png', 'gif'].includes(parsedContent.ext)">
                    <img :src="previewUrl" alt="预览图片" class="preview-image" />
                </template>
                <template v-else-if="['doc', 'docx'].includes(parsedContent.ext)">
                    <preview-doc :src="previewUrl"></preview-doc>
                </template>
                <template v-else>
                    <!--txt md 文件-->
                    <RxMarkDown
                        style="width:100%;height:100%;"
                        ref="rxMarkDown"
                        :onInit="initMarkdown"
                        :readonly="true"
                        :key="parsedContent.fileId"
                    />
                </template>
            </template>
        </div>
        <div v-if="loading" class="loading-message">加载中...</div>
        <div v-if="error" class="error-message">{{ error }}</div>
    </div>
</template>

<script setup>
import { ref, defineProps, onMounted, computed, watch } from 'vue';
import { TokenUtil, Util } from "@lowcode/jpaas-base-lib";
import previewDoc from './preview-file-doc.vue'
import previewExcel from './preview-file-excel.vue'
import {RxMarkDown} from '@lowcode/jpaas-share-component';
import rxAjax from '@/assets/js/ajax.js';
// 定义组件的 props
const props = defineProps({
    selectedKnowledge: {
        type: Object,
        default: {}
    },
});

// 初始化响应式数据
const previewUrl = ref('');
const loading = ref(false);
const error = ref('');
const rxMarkDown = ref(null);
const getPath = async (file, type, isScale = false) => {
    let token = TokenUtil.getToken();
    let fileId = Util.encryptWord(file);
    if (['jpg', 'jpeg', 'png', 'gif'].includes(type)) {
        return `/api/api-system/system/core/sysFile/previewImg?fileId=${fileId}&accessToken=${token}&isScale=${isScale}`;
    } else {
        return `/api/api-system/system/core/sysFile/previewFile?fileId=${fileId}&accessToken=${token}`;
    }
};
// 新增解析后的内容计算属性
const parsedContent = computed(() => {
    try {
        if (typeof props.selectedKnowledge.content === 'string') {
            return JSON.parse(props.selectedKnowledge.content);
        }
        return props.selectedKnowledge.content;
    } catch (e) {
        console.error('解析内容失败:', e);
        return null;
    }
});

// 修改获取预览URL的逻辑
const fetchPreviewUrl = async () => {
    try {
        loading.value = true;
        error.value = '';
        const result = await getPath(parsedContent.value.fileId, parsedContent.value.ext);
        if (result) {
          previewUrl.value = result;
        }
    } catch (err) {
      console.log('err:',err)
    } finally {
        loading.value = false;
    }
};

const initMarkdown = async () => {
    let token = TokenUtil.getToken();
    let fileId = Util.encryptWord(parsedContent.value.fileId);
    let url = "/api-system/system/core/sysFile/previewFile?fileId=" + fileId + "&accessToken=" + token;
    let res = await rxAjax.get(url);
    rxMarkDown.value.content = res;
};

// 添加对selectedKnowledge的监听
watch(() => props.selectedKnowledge, (newVal, oldVal) => {
  // 添加类型过滤和有效性校验
  if (newVal?.type === 'file' && newVal?.id !== oldVal?.id) {
    fetchPreviewUrl();
  }
}, { immediate: true, deep: true });
</script>

<style scoped>
.preview-container {
    background-color: #fff;
    box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 12px 0px;
    border-radius: 4px;
    padding: 10px;
    height: 100%;
}

.preview-content {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    overflow-x: hidden;
}

.preview-title {
    font-size: 20px;
    font-weight: 600;
    color: #374151;
    margin-bottom: 16px;
    text-align: center;
}

.preview-image {
    margin: 0 auto;
    height: auto;
    max-width: 100%;
    border-radius: 4px;
}

.preview-iframe {
    width: 100%;
    height:  100%;
    border-radius: 4px;
}

.loading-message {
    font-size: 16px;
    color: #6b7280;
    text-align: center;
}

.error-message {
    font-size: 16px;
    color: #ef4444;
    text-align: center;
}
</style>
